package com.tools.scanner.utils

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import com.tools.scanner.QrApp
import java.util.Stack
import kotlin.system.exitProcess

object ActivityStack {
    private val activityStack: Stack<Activity> = Stack()

    fun pushActivity(activity: Activity) {
        activityStack.push(activity)
    }

    fun popActivity(): Activity? {
        return if (activityStack.isNotEmpty()) {
            activityStack.pop()
        } else {
            null
        }
    }

    fun exitApp() {
        removeAllActivity()

        val activityManager = QrApp.app.getSystemService(Context.ACTIVITY_SERVICE)
        if (activityManager is ActivityManager) {
            val myPid = android.os.Process.myPid()
            val runningAppProcesses = activityManager.runningAppProcesses

            for (processInfo in runningAppProcesses) {
                if (processInfo.pid != myPid) {
                    android.os.Process.killProcess(processInfo.pid)
                }
            }

            android.os.Process.killProcess(myPid)
            exitProcess(0)
        }
    }

    private fun removeAllActivity() {
        while (activityStack.isNotEmpty()) {
            activityStack.pop().finish()
        }
    }
}